package org.yan.kangaroo.auth.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.yan.kangaroo.auth.config.security.SecurityConstant;
import org.yan.kangaroo.auth.config.security.SecurityUserDetails;
import org.yan.kangaroo.common.util.JsonUtils;

import java.util.Date;

/**
 * @author wangx
 * @date 11/11/2019 16:57
 */
@Slf4j
public class JwtUtils {
    private JwtUtils() {
    }

    public static String createToken(SecurityUserDetails userDetails) {
        String jwt = Jwts.builder()
                .setSubject(userDetails.getUsername())
                .claim(SecurityConstant.TOKEN_USER_INFO, JsonUtils.getInstance().toJson(userDetails))
                .setExpiration(new Date(System.currentTimeMillis() + SecurityConstant.TOKEN_EFFECTIVE_TIME))
                .signWith(SignatureAlgorithm.HS512, SecurityConstant.JWT_SIGN_KEY)
                .compact();
        return SecurityConstant.TOKEN_PREFIX + jwt;
    }


    public static Claims getTokenContent(String token) {

        return Jwts.parser().setSigningKey(SecurityConstant.JWT_SIGN_KEY)
                .parseClaimsJws(token.replace(SecurityConstant.TOKEN_PREFIX, ""))
                .getBody();

    }
}
